//
//  PhotoBrowserAnimator.swift
//  XinLangWeiBo
//
//  Created by mac on 15/12/4.
//  Copyright © 2015年 mac. All rights reserved.
//

import UIKit

// MARK: - 照片浏览器展现转场代理
protocol PhotoBrowserPresentDelegate: NSObjectProtocol {
    
    /// 参与转场动画的图像视图
    ///
    /// - parameter indexPath: 照片索引
    ///
    /// - returns: 参与转场动画的全新图像视图
    func imageViewForPresent(indexPath: NSIndexPath) -> UIImageView
    
    /// 展现转场图像起始位置
    ///
    /// - parameter indexPath: 照片索引
    ///
    /// - returns: 相对于屏幕的位置
    func photoBrowserPresentFromRect(indexPath: NSIndexPath) -> CGRect
    
    /// 展现动画结束时的屏幕位置
    ///
    /// - parameter indexPath: 照片索引
    ///
    /// - returns: 相对于屏幕的位置
    func photoBrowserPresentToRect(indexPath: NSIndexPath) -> CGRect
}


class PhotoBrowserAnimator: NSObject ,UIViewControllerTransitioningDelegate{

    /// 是否展现标记
    private var isPresented = false
    
     /// 返回`提供展现动画`的对象
    func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        
        
        isPresented = true
        return self;
    }
    
    func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        
         isPresented = false
        return self;
    }
}

extension PhotoBrowserAnimator : UIViewControllerAnimatedTransitioning {
    //返回动画时长
    func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
        return 2
    }
    
    //动画具体实现
    func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
        
        
        isPresented ? presentAnimation(transitionContext) : dismissAnimation(transitionContext)

    }
    
    
    /// 解除转场动画
    ///
    /// - parameter transitionContext: 转场上下文
    private func dismissAnimation(transitionContext: UIViewControllerContextTransitioning) {
        
        let fromView = transitionContext.viewForKey(UITransitionContextFromViewKey)!
        
        UIView.animateWithDuration(transitionDuration(transitionContext), animations: {
            
            fromView.alpha = 0.0
            
            }) { _ in
                
                fromView.removeFromSuperview()
                transitionContext.completeTransition(true)
        }
    }
    
    
    private func presentAnimation(transitionContext: UIViewControllerContextTransitioning) {
        
        let toView = transitionContext.viewForKey(UITransitionContextToViewKey)!
        toView.alpha = 0.0
        
        transitionContext.containerView()?.addSubview(toView)
        
        UIView.animateWithDuration(transitionDuration(transitionContext), animations: {
            
            toView.alpha = 1.0
            
            }) { _ in
                
                transitionContext.completeTransition(true)
        }
    }
    
}